<template>
  <div class="water-quality-container">

    <div class="popup-header">
      <h3>{{ '饮用水源地详情' }}</h3>
    </div>

    <div class="tab-container">
      <!-- 标签栏不变 -->
      <div class="tab-nav">
        <div v-for="(tab, index) in tabs" :key="index" class="tab-nav-item"
          :class="{ active: activeTabIndex === index }" @click="switchTab(index)">
          {{ tab.title }}
        </div>
      </div>

      <!-- 内容区添加动画：transition-group 包裹 -->
      <div class="tab-content">
        <transition-group name="tab-fade" mode="out-in">
          <div v-for="(tab, index) in tabs" :key="index" class="tab-panel" v-show="activeTabIndex === index">
            <div v-if="index === 0">
              <div class="body">
                <div class="base-info-box">
                  <div class="base-info-grid">
                    <div class="base-info-item">
                      <span class="base-info-label">站点名称</span>
                      <span class="base-info-value">{{ featureData.segmentname || '--' }}</span>
                    </div>
                    <div class="base-info-item">
                      <span class="base-info-label">河流名称</span>
                      <span class="base-info-value">{{ featureData.rivername || '--'
                      }}</span>
                    </div>
                    <div class="base-info-item">
                      <span class="base-info-label">行政区划</span>
                      <span class="base-info-value">{{ featureData.county || '--'
                      }}</span>
                    </div>

                    <div class="base-info-item">
                      <span class="base-info-label">断面类型</span>
                      <span class="base-info-value info-value">{{ featureData.controllevel || '--' }}</span>
                    </div>
                    <div class="base-info-item">
                      <span class="base-info-label">经纬度</span>
                      <span class="base-info-value">{{ formatLngLat.lng || '--' }}, {{ formatLngLat.lat || '--'
                        }}</span>
                    </div>
                    <div class="base-info-item">
                      <span class="base-info-label">目标水质</span>
                      <span class="base-info-value">{{ featureData.targetlevelname || '--' }}</span>
                    </div>
                  </div>
                  <div class="base-info-item-line margin-top-12">
                    <span class="base-info-label-line">所在地址</span>
                    <span class="base-info-value-line">{{ featureData.segmaddress || '--' }}</span>
                  </div>
                </div>

              </div>
            </div>
            <div v-else>
              <!-- 水质状况区域 -->
              <div class="body">
                <!-- select选择框 -->
                <div class="select-container">
                  <van-cell-group inset class="select-cell-group">
                    <!-- <van-field  clickable label="监测项目" :value="fieldValue" placeholder="请选择监测项目"
            @click="showSelectPicker = true" />-->
                    <van-field v-model="fieldValue" is-link readonly label="监测因子" placeholder="请选择监测项目"
                      @click="showSelectPicker = true" />
                  </van-cell-group>
                </div>

                <!-- 图表容器 -->
                <div class="chart-container ">
                  <div class="chart-wrapper">
                    <div ref="chartRef" class="echart-container"></div>
                  </div>
                </div>

              </div>
            </div>
          </div>
        </transition-group>
      </div>
    </div>



    <!-- 选择器 -->
    <van-popup v-model:show="showSelectPicker" position="bottom" round>
      <van-picker v-model="selectedOption" :columns="selectOptions" title="请选择监测项目" confirm-button-text="确认"
        cancel-button-text="取消" @confirm="onSelectConfirm" @cancel="showSelectPicker = false" />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, computed, watch } from 'vue'
import * as echarts from 'echarts'
import {

  Field as VanField,
  CellGroup as VanCellGroup,
  Popup as VanPopup,
  Picker as VanPicker,
  showToast
} from 'vant'
import { drinkwateritemlistbytime, bussinessItemData } from '@/api/shuiyuandi'
import { formatCoordObjectToSixDecimals } from '../../utils/coordtransform_utils.js';

// Props
const props = defineProps({
  featureId: {
    type: String,
    default: ''
  },
  featureData: {
    type: Object,
    default: () => ({})
  }
})

// Data
// const autoStationInfo = ref({})
const dateRange = ref([])
const dateRangeTemp = ref([])
// const showDatePicker = ref(false)
const showSelectPicker = ref(false)
// const indicators = ref([])
const times = ref([])
const qualityData = ref([])
const monitoringData = ref({})
const chart = ref(null)
const chartRef = ref(null)

const selectOptions = ref([])
const selectedOption = ref([])
const fieldValue = ref('')

const formatLngLat = ref({})

const activeTabIndex = ref(0);
const tabs = ref([
  { title: '基础信息' },
  { title: '趋势图' },
]);

const switchTab = (index) => {
  activeTabIndex.value = index;
};

// Methods
const formatDate = (date) => {
  if (!date) return ''
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

const initDateRange = () => {
  const end = new Date()
  const start = new Date()
  start.setHours(0, 0, 0, 0)
  end.setHours(0, 0, 0, 0)
  start.setTime(start.getTime() - 3600 * 1000 * 24 * 30 * 6) // 前6个月
  dateRange.value = [start, end]
  dateRangeTemp.value = [start, end]
}

const getBussinessItemData = () => {
  bussinessItemData({ bussinessCategoryCode: "DrinkAuto" }).then(res => {
    if (res && Array.isArray(res.data)) {
      selectOptions.value = res.data.map(item => ({
        text: item.itemName,
        value: item.itemCode
      }))
      if (selectOptions.value.length > 0) {
        selectedOption.value = [selectOptions.value[0].value]
        fieldValue.value = selectOptions.value[0].text
        getMonitoringData()
      }
    } else {
      selectOptions.value = []
    }
  }).catch(error => {
    selectOptions.value = []
    console.error('Failed to fetch business item data:', error)
  })
}

const getOption = () => {
  const option = {
    title: {
      text: '水质趋势图',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      },
      padding: [0, 0, 20, 0]
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255, 255, 255, 0.9)',
      borderColor: '#ddd',
      borderWidth: 1,
      textStyle: {
        color: '#333'
      },
      formatter: "{b}: {c} ",
      // formatter: params => {
      //   let result = `<div style="font-weight:bold">时间: ${params[0].name}</div>`
      //   params.forEach(item => {
      //     if (item.seriesType === 'line') {
      //       result += `<div style="display:flex;align-items:center;margin-top:5px">
      //         <span style="display:inline-block;width:10px;height:10px;background-color:${item.color};margin-right:5px;border-radius:50%"></span>
      //         ${item.seriesName}: ${item.value}
      //       </div>`
      //     }
      //   })
      //   return result
      // }
    },
    legend: {
      show: true,
      top: 'bottom',
      left: 'center'
    },
    grid: {
      left: '3%',
      right: '7%',
      bottom: '20%',
      top: '15%',
      containLabel: true
    },
    // toolbox: {
    //   feature: {
    //     saveAsImage: {
    //       title: '保存图片'
    //     },
    //     dataZoom: {
    //       title: {
    //         zoom: '区域缩放',
    //         back: '缩放还原'
    //       }
    //     },
    //     restore: {
    //       title: '还原'
    //     }
    //   }
    // },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: times.value,
      name: '监测时间',
      nameLocation: 'middle',
      nameGap: 30
    },
    yAxis: [
      {
        type: 'value',
        nameLocation: 'middle',
        nameGap: 50,
        splitLine: {
          lineStyle: {
            color: 'rgba(0, 0, 0, 0.05)'
          }
        }
      }
    ],
    series: [
      {
        // name: '水质',
        type: 'line',
        data: qualityData.value,
        symbol: 'circle',
        symbolSize: 6,
        emphasis: {
          symbolSize: 8
        },
        lineStyle: {
          width: 3,
          color: '#4bc0c0'
        },
        itemStyle: {
          color: '#4bc0c0'
        },
        smooth: true
      }
    ],
    dataZoom: [
      {
        type: 'inside',
        xAxisIndex: 0,
        start: 0,
        end: 100
      },
      {
        show: true,
        type: 'slider',
        xAxisIndex: 0,
        start: 0,
        end: 100,
        bottom: 50
      }
    ],
    animation: true,
    animationDuration: 1000,
    animationEasing: 'cubicOut'
  }
  return option
}

const renderChart = () => {
  if (!chartRef.value) {
    console.warn('图表容器未找到')
    return
  }

  if (chart.value) {
    chart.value.dispose()
  }

  chart.value = echarts.init(chartRef.value)
  const option = getOption()
  chart.value.setOption(option, true)
}

const convertData = (data) => {
  // 参数验证
  if (!Array.isArray(data)) {
    return {
      dateList: [],
      value: []
    }
  }

  // 一次遍历完成所有数据处理
  const dateList = []
  const valueList = []

  for (let i = 0; i < data.length; i++) {
    const item = data[i]
    if (item && typeof item === 'object') {
      dateList.push(item.sampleDate)
      // 安全的数值转换
      const parsedValue = parseFloat(item.effectiveValue)
      valueList.push(isNaN(parsedValue) ? 0 : parsedValue)
    }
  }

  return {
    dateList,
    value: valueList
  }
}

const getMonitoringData = () => {

  if (!dateRange.value || dateRange.value.length !== 2) {
    showToast('请选择开始时间和结束时间')
    return
  }

  if (dateRange.value[0] > dateRange.value[1]) {
    showToast('开始时间不能晚于结束时间')
    return
  }
  console.log('Getting monitoring data...')
  const startTime = formatDate(dateRange.value[0])
  const endTime = formatDate(dateRange.value[1])

  drinkwateritemlistbytime({
    segmentId: props.featureId,
    beginDate: startTime,
    endDate: endTime,
    itemCode: selectedOption.value[0]
  }).then(res => {
    console.log("res", res)
    monitoringData.value = convertData(res.data.list)
    times.value = monitoringData.value.dateList
    qualityData.value = monitoringData.value.value
    renderChart()
  }).catch(error => {
    console.error('获取监测数据失败:', error)
    showToast('获取监测数据失败')
  })
}



// Events
// const onDateConfirm = ({ selectedValues }) => {
//   dateRange.value = selectedValues
//   showDatePicker.value = false
//   getMonitoringData()
// }
const onSelectConfirm = ({ selectedValues, selectedOptions }) => {
  showSelectPicker.value = false;
  selectedOption.value = selectedValues;
  fieldValue.value = selectedOptions[0].text;
};


// Watch
watch(() => props.featureId, (newVal) => {
  if (newVal) {
    console.log('featureId', newVal)
  }
}, { immediate: true })

// Lifecycle
onMounted(() => {
  console.log('onMounted', 111111111111111)
  console.log('props.featureData', props.featureData)
  formatLngLat.value = formatCoordObjectToSixDecimals(props.featureData);
  console.log('formatLngLat', formatLngLat)
  initDateRange()
  getBussinessItemData()
  window.addEventListener('resize', () => {
    if (chart.value) {
      chart.value.resize()
    }
  })
})

onBeforeUnmount(() => {
  if (chart.value) {
    chart.value.dispose()
  }
  window.removeEventListener('resize', () => {
    if (chart.value) {
      chart.value.resize()
    }
  })
})
</script>

<style scoped>
/* 基础样式不变，新增动画样式 */
/* 淡入淡出动画 */
.tab-fade-enter-from,
.tab-fade-leave-to {
  opacity: 0;
  transform: translateY(10px);
}

.tab-fade-enter-active,
.tab-fade-leave-active {
  transition: opacity 0.3s ease, transform 0.3s ease;
}

.tab-fade-leave-from,
.tab-fade-enter-to {
  opacity: 1;
  transform: translateY(0);
}

/* 其他样式同基础版... */
.tab-container {
  padding: 15px;
   /* 占满剩余空间 */
  flex: 1;
  /* 启用垂直滚动 */
  overflow-y: auto;
  /* 优化iOS滚动体验 */
  -webkit-overflow-scrolling: touch;
  /* 隐藏滚动条 */
  -ms-overflow-style: none;
  scrollbar-width: none;
}


/* Tab 标签栏样式 */
.tab-nav {
  display: flex;
  gap: 2px;
  border-bottom: 1px solid #e5e7eb;
  padding-bottom: 4px;
}

.tab-nav-item {
  padding: 12px 24px;
  cursor: pointer;
  font-size: 16px;
  color: #6b7280;
  border-radius: 8px 8px 0 0;
  transition: all 0.2s ease;
}

/* 激活态样式 */
.tab-nav-item.active {
  color: #1890ff;
  font-weight: 600;
  background-color: #f0f7ff;
  border-bottom: 2px solid #1890ff;
}

.tab-nav-item:hover:not(.active) {
  background-color: #f9fafb;
}


/* 主要容器样式 */
.water-quality-container {
  max-width: 100%;
  width: 100%;
  margin: 0;
  border-radius: 0;
  padding: 0;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4edf5 100%);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  /* 设置容器高度为视口高度 */
  height: 80vh;
  /* 确保在不同设备上正常显示 */
  position: fixed;
}


/* 触摸滚动通用样式 */
.touch-scroll {
  -webkit-overflow-scrolling: touch;
  -ms-overflow-style: none;
  scrollbar-width: none;
}

/* 隐藏滚动条但保持功能 */
.touch-scroll::-webkit-scrollbar {
  display: none;
}

/* 弹窗头部样式 */
.popup-header {
  font-size: 18px;
  font-weight: 600;
  padding: 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}





/* 隐藏滚动条但保持功能 */
.tab-container ::-webkit-scrollbar {
  display: none;
}

.select-cell-group {
  margin: 0;
}

.chart-container {
  background: white;
  border-radius: 16px;
  padding: 15px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  margin-top: 20px;
  margin-bottom: 20px;
}

.chart-wrapper {
  background: #fafafa;
  border-radius: 10px;
  padding: 10px;
}

.echart-container {
  width: 100%;
  height: 350px;
}



.elevated-card {
  background: linear-gradient(145deg, #ffffff, #f8f9fa);
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.elevated-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.12);
}

@media (max-width: 768px) {

  /* 进一步优化移动设备上的滚动体验 */
  .tab-container {
    padding: 12px;
    -webkit-overflow-scrolling: touch;
  }

  .echart-container {
    height: 300px;
  }

  .chart-container {
    padding: 10px;
  }
}

/* 为触摸设备添加特殊样式 */
@media (hover: none) and (pointer: coarse) {

  /* 优化滚动效果 */
  .tab-container {
    -webkit-overflow-scrolling: touch;
    scroll-behavior: smooth;
  }
}


/* 基础信息卡片样式 */
.base-info-box {
  background: white;
  border-radius: 16px;
  padding: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  margin-bottom: 20px;
  border: 1px solid #f0f0f0;
  transition: all 0.3s ease;
}

.base-info-box:hover {
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.12);
}

/* 标题区域样式 */
.base-info-title {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 12px;
  border-bottom: 1px solid #eee;
  margin-bottom: 12px;
}


/* 信息网格布局 */
.base-info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

/* 信息项样式 */
.base-info-item {
  display: flex;
  justify-content: space-between;
  flex-direction: column;
  align-items: center;
  padding: 12px 8px;
  background: linear-gradient(135deg, #f8f9fa, #e9ecef);
  border-radius: 12px;
  transition: all 0.3s ease;
}

.base-info-item:hover {
  background: linear-gradient(135deg, #f0f2f5, #dde1e6);
}

/* 标签和值的样式 */
.base-info-label {
  font-weight: 500;
  color: #7f8c8d;
  font-size: 12px;
}

.base-info-value {
  margin-top: 4px;
  font-weight: 700;
  color: #2c3e50;
  font-size: 14px;
  border-radius: 20px;
  align-items: center;
  justify-content: center;
  text-align: center;
  display: flex;
  height: 100%;
}


.margin-top-12 {
  margin-top: 18px;
}

.base-info-item-line {
  display: flex;
  flex-direction: row;
  align-items: center;
  padding: 12px 16px;
  background: linear-gradient(135deg, #f8f9fa, #e9ecef);
  border-radius: 12px;
  transition: all 0.3s ease;
}

.base-info-item-line:hover {
  background: linear-gradient(135deg, #f0f2f5, #dde1e6);
}

/* 标签和值的样式 */
.base-info-label-line {
  font-weight: 500;
  color: #7f8c8d;
  font-size: 12px;
}

.base-info-value-line {
  margin-left: 12px;
  font-weight: 700;
  color: #2c3e50;
  font-size: 14px;
}

</style>